package com.biz.primus.app.rest.handler.impl;

import com.biz.primus.app.rest.handler.BuildRequestHandler;
import com.biz.primus.base.enums.user.ClientTypes;
import com.biz.primus.base.exception.BizBusinessException;
import com.biz.primus.base.vo.handler.ClientTypeAware;
import com.biz.primus.base.global.GlobalParams;
import com.biz.primus.base.vo.handler.IRequestVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 感知client type并与vo绑定
 *
 * @author jun.liu
 * @usage
 * @reviewer
 * @since 2017年11月3日
 */
@Component
@Slf4j
public class ClientTypeHandler implements BuildRequestHandler
{

    @Override
    public void handle(HttpServletRequest request, IRequestVo requestVo)
            throws BizBusinessException
    {
        if (requestVo instanceof ClientTypeAware)
        {
            ClientTypeAware aware = (ClientTypeAware) requestVo;
            // 实现了全局参数接口,client type从全局参数中取
            GlobalParams gp = requestVo.getGlobalParams();
            String os = gp.getOs();
            if (StringUtils.isNotBlank(os))
            {
                switch (os) {
                    case "iOS":
                        aware.setClientType(ClientTypes.ios);
                        break;
                    case "androId":// 大写I就是这么任性
                        aware.setClientType(ClientTypes.android);
                        break;
                    default:
                        throw new BizBusinessException("全局参数中的os属性无法解析,os=[" + os + "]");
                }
            }
            else
            {
                // 否则取请求头定的userAgent
                log.warn("全局参数中的os为空");
                String userAgent = request.getHeader("User-Agent");
                if (StringUtils.isNotBlank(userAgent))
                {
                    boolean contains = userAgent.toLowerCase()
                            .contains("micromessenger");
                    if (contains)
                    {
                        aware.setClientType(ClientTypes.wechat);
                    }
                    else
                    {
                        aware.setClientType(ClientTypes.web);
                    }
                }
                else
                {
                    log.warn("user-agent为空,未能获取到clientType");
                    aware.setClientType(ClientTypes.unknown);
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return BuildRequestHandler.ClientTypeHandlerOrderValue;
    }

}
